from django.shortcuts import render
from rest_framework.views import APIView
from random import randint
import logging
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status

from celery_tasks.sms.tasks import send_sms_code

# 创建日志输出器对象
logger = logging.getLogger('django')


# Create your views here.
class SMSCodeView(APIView):
    """发送短信验证码"""

    def get(self, request, mobile):
        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 来发送验证码之前先去redis中取一下发送短信标记
        # pl.get('sms_flag_%s' % mobile)
        # flag = pl.execute()
        flag = redis_conn.get('sms_flag_%s' % mobile)
        if flag:  # 只要if成功说明当前号码60s内发过短信了
            return Response({'message': '频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)

        # 创建redis管道
        pl = redis_conn.pipeline()

        # 把验证码存储到redis
        # redis_conn.setex(key, 过期时间, value)
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, 300, sms_code)
        # 存储一个已经发送过验证码的标识
        # redis_conn.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('sms_flag_%s' % mobile, 60, 1)

        # 执行管道(执行管道时,才会把管道中的多个redis命令一次全部执行)
        pl.execute()

        # # 使用容联云通讯发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        # send_sms_code(mobile, sms_code)  # 不要直接调用,直接调用等于还是直接执行了耗时操作
        send_sms_code.delay(mobile, sms_code)
        # 响应
        return Response({'message': 'ok'})
